/**
 * CopyRight © 2012 USTC SINOVATE SOFTWARE CO.LTD All Rights Reserved.
 */

package com.cmcc.zysoft.infocollection.mobile.service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import com.cmcc.zysoft.infocollection.mobile.dao.MDeviceDao;
import com.cmcc.zysoft.infocollection.model.Device;
import com.cmcc.zysoft.infocollection.util.MD5Tools;
import com.starit.common.dao.hibernate.HibernateBaseDao;
import com.starit.common.dao.service.BaseServiceImpl;

/**
 * @author 袁凤建
 * <br />邮箱: yuan.fengjian@ustcinfo.com
 * <br />描述: DeviceService.java
 * <br />版本: 1.0.0
 * <br />日期: 2013-8-8 上午9:32:58
 * <br />CopyRight © 2012 USTC SINOVATE SOFTWARE CO.LTD All Rights Reserved.
 */

@Service
public class MDeviceService extends BaseServiceImpl<Device, String> {

	@Resource
	private MDeviceDao mDeviceDao;
	
	@Override
	public HibernateBaseDao<Device, String> getHibernateBaseDao() {
		return this.mDeviceDao;
	}
	
	/**
	 * 根据imei+imsi+手机号生成设备号.如果已存在,则修改数据,否则则插入.
	 * @param userId 用户ID
	 * @param mobile 手机号
	 * @param imei imei号
	 * @param imsi imsi号
	 * @return String
	 */
	public String addOrUpdateRegistercode(String userId, String mobile, String imei, String imsi) {
		String deviceId = this.mDeviceDao.getDeviceId(mobile);
		String code = imei + imsi + mobile;
		String registerCode = MD5Tools.encodePassword(code, null);
		if(StringUtils.hasText(deviceId)) {
			Device device = this.mDeviceDao.get(deviceId);
			device.setAddDate(new Date());
			device.setImei(imei);
			device.setImsi(imsi);
			device.setRegisterCode(registerCode);
			this.mDeviceDao.update(device);
			return deviceId;
		} else {
			Device device = new Device();
			device.setEmployeeId(userId);
			device.setImei(imei);
			device.setImsi(imsi);
			device.setRegisterCode(registerCode);
			device.setStatus("1");
			deviceId = this.mDeviceDao.save(device);
			if(StringUtils.hasText(deviceId)) {
				return deviceId;
			} else {
				return "";
			}
		}
	}
	
	/**
	 * 对IMSI号、IMEI号做鉴权.
	 * @param userId 用户ID
	 * @param IMEI IMEI号
	 * @param IMSI IMSI号
	 * @return Boolean 通过-true,未通过-false
	 */
	public Boolean check(String userId, String IMEI, String IMSI) {
		List<Map<String, Object>> list = this.mDeviceDao.check(userId, IMEI, IMSI);
		if(!list.isEmpty()) {
			return true;
		}
		return false;
	}
}